package com.datamanage.processing.controller;

import com.datamanage.processing.dto.ProcessingTaskDTO;
import com.datamanage.processing.entity.ProcessingTask;
import com.datamanage.processing.service.ProcessingTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/tasks")
public class ProcessingTaskController {
    
    @Autowired
    private ProcessingTaskService processingTaskService;
    
    @PostMapping
    public ResponseEntity<?> createTask(@RequestBody ProcessingTaskDTO taskDTO, 
                                     @RequestHeader("CompanyId") Long companyId,
                                     @RequestHeader("UserId") Long userId) {
        try {
            ProcessingTask task = processingTaskService.createTask(taskDTO, userId, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("task", task);
            response.put("message", "任务创建成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getTaskById(@PathVariable Long id, 
                                      @RequestHeader("CompanyId") Long companyId) {
        Optional<ProcessingTask> task = processingTaskService.getTaskById(id, companyId);
        if (task.isPresent()) {
            return ResponseEntity.ok(task.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<?> getAllTasks(@RequestHeader("CompanyId") Long companyId,
                                      @RequestParam(defaultValue = "0") int page,
                                      @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<ProcessingTask> tasks = processingTaskService.getAllTasks(companyId, pageable);
        return ResponseEntity.ok(tasks);
    }
    
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getTasksByUserId(@PathVariable Long userId,
                                           @RequestHeader("CompanyId") Long companyId,
                                           @RequestParam(defaultValue = "0") int page,
                                           @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<ProcessingTask> tasks = processingTaskService.getTasksByUserId(userId, companyId, pageable);
        return ResponseEntity.ok(tasks);
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getTasksByStatus(@PathVariable String status,
                                           @RequestHeader("CompanyId") Long companyId,
                                           @RequestParam(defaultValue = "0") int page,
                                           @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<ProcessingTask> tasks = processingTaskService.getTasksByStatus(status, companyId, pageable);
        return ResponseEntity.ok(tasks);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable Long id, 
                                     @RequestBody ProcessingTaskDTO taskDTO,
                                     @RequestHeader("CompanyId") Long companyId,
                                     @RequestHeader("UserId") Long userId) {
        try {
            ProcessingTask task = processingTaskService.updateTask(id, taskDTO, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("task", task);
            response.put("message", "任务更新成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable Long id, 
                                     @RequestHeader("CompanyId") Long companyId,
                                     @RequestHeader("UserId") Long userId) {
        try {
            processingTaskService.deleteTask(id, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("message", "任务删除成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/{id}/start")
    public ResponseEntity<?> startTask(@PathVariable Long id, 
                                    @RequestHeader("CompanyId") Long companyId,
                                    @RequestHeader("UserId") Long userId) {
        try {
            ProcessingTask task = processingTaskService.startTask(id, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("task", task);
            response.put("message", "任务启动成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/{id}/stop")
    public ResponseEntity<?> stopTask(@PathVariable Long id, 
                                   @RequestHeader("CompanyId") Long companyId,
                                   @RequestHeader("UserId") Long userId) {
        try {
            ProcessingTask task = processingTaskService.cancelTask(id, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("task", task);
            response.put("message", "任务停止成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}